package org.xurui.sxl.protocol.command.impl;

import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.event.EventMessage;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;
import org.xurui.sxl.protocol.utils.NumberUtils;
import org.xurui.sxl.protocol.utils.SxlMessageUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 温度上报
 */
public class CmdCodec_TEMPERTURE implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.TEMPERTURE.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return false;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //温度上报 设备上报
        //格式：*XX,YYYYYYYYYYYYYYY,TEMPERTURE,HHMMSS,TEMPERTURE_NUM,DDMMYY,tracker_status#
        //例子：*TP,866104040001458,TEMPERTURE,130305,36.52,271112,FFFFFFFF#
        //回复格式：*XX,YYYYYYYYYYYYYYY,V4,TEMPERTURE,seq,HHMMSS#
        //回复示例：*TP,866104040001458,V4,TEMPERTURE,130305,130305#
        //参数说明：TEMPERTURE_NUM 温度数据，如 36.52。
        //解析数据为事件上报
        EventMessage eventMessage = new EventMessage();
        //ReportPropertyMessage report = ReportPropertyMessage.create();
        String[] payloadArr = payload.replaceAll("\\*", "").split(",");
        String deviceId = payloadArr[1];
        eventMessage.setEvent(CommandEnum.TEMPERTURE.name());
        eventMessage.setDeviceId(deviceId);
        eventMessage.setMessageId(deviceId + "_" + payloadArr[3]);
        Map<String, Object> properties = new HashMap<>();
        properties.put("temperatureNum", NumberUtils.parseDouble(payloadArr[4]));
        properties.put("uptime",payloadArr[3]);
        properties.put("upday",payloadArr[5]);
        String trackerStatusHex = payloadArr[6];

        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        //report.setProperties(properties);
        eventMessage.setData(properties);
        //回复设备数据
        //TODO 暂时没找到设备回复消息的方法
       /* String day= BinaryUtils.getDateFormat();
        String reply="*"+payloadArr[0]+","+deviceId+",V4,"+CommandEnum.TEMPERTURE.name()+","+payloadArr[3]+","+day;
        context.getSession()
            .send(EncodedMessage
                .simple(Unpooled.wrappedBuffer(reply.getBytes())))
            .subscribe();*/
        SxlMessageUtils.bulidAndSend2DeviceV4Msg(context,payloadArr[0],deviceId,CommandEnum.TEMPERTURE.name(),payloadArr[3]);
        //return genDeviceMessage(report);
        return genDeviceMessage(eventMessage);
    }
}
